<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="false">
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
        <a-row :gutter="48">
          <template v-if="contentFlag" >
            <a-col :span="12">
              <a-form-model-item label="项目名称" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="projectId">
                <select-project-input
                  v-model="model.projectId"
                  placeholder="请输入选择项目"
                  :queryParamType="'1'"
                  :teamId="teamId"
                  :companyId="applicant"
                  :disabled="formDisabled || !teamId || !applicant || showFlowSubmitButton"
                  @input="selectProject" />
              </a-form-model-item>
            </a-col>
            <a-col :span="12">
              <a-form-model-item label="项目编号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="projectCode">
                <a-input disabled v-model="model.projectCode" placeholder="请输入项目编号" style="width: 100%" />
              </a-form-model-item>
            </a-col>
            <a-col :span="12">
              <a-form-model-item label="业绩归属年度" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="performanceAttributionYear">
                <j-dict-select-tag
                  type="list"
                  v-model="model.performanceAttributionYear"
                  dictCode="yjgsnd"
                  placeholder="请选择业绩归属年度"
                  disabled/>
              </a-form-model-item>
            </a-col>
            <a-col :span="12">
              <a-form-model-item label="合同名称" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="relContractId">
                <select-contract-manager-input
                  showName="1"
                  :allowClear="true"
                  isCategoryType="2"
                  :muitFlag="true"
                  :disabled="formDisabled || !model.projectId || showFlowSubmitButton"
                  :projectId="model.projectId"
                  htlx="2"
                  v-model="model.relContractId" />
              </a-form-model-item>
            </a-col>
            <a-col :span="12">
              <a-form-model-item label="任务分类" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="taskCategory">
                <select-project-task-input
                  :is-flow-cancel="'running'"
                  :disabled="formDisabled || showFlowSubmitButton"
                  :isRefresh="true"
                  v-model="model.taskCategory"
                  :projectId="model.projectId"
                  @back="changeTask"/>
              </a-form-model-item>
            </a-col>
            <!-- <a-col :span="12">
            <a-form-model-item label="任务说明" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="taskName">
              <a-input :disabled=formDisabled v-model="model.taskName" placeholder="请输入任务说明"  disabled></a-input>
            </a-form-model-item>
          </a-col> -->
            <!-- 迭代八需求文档 - 3.1.9 费用报销单 费用类别-费用类-费用报销信息-子表-新增（含列表）删除费用所属团队和费用所属年度两个字段 -->
            <!-- <a-col :span="12">
            <a-form-model-item label="费用所属年度" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="teamYear">
              <j-dict-select-tag :disabled=formDisabled type="list" v-model="model.teamYear" dictCode="tdnd_type" placeholder="请选择费用所属年度" />
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="费用所属团队" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="teamId">
              <select-team-input
                  :disabled=formDisabled
                  v-model="model.teamId" :tdlx="3" disabled/>
            </a-form-model-item>
          </a-col> 
            <a-col :span="12">
              <a-form-model-item label="业绩归属年度" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="performanceAttributionYear">
                <j-dict-select-tag
                  type="list"
                  v-model="model.performanceAttributionYear"
                  dictCode="yjgsnd"
                  placeholder="请选择业绩归属年度"
                  disabled/>
              </a-form-model-item>
            </a-col>-->
          </template>
          <a-col :span="12">
            <a-form-model-item label="费用大类" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="bigCategory">
              <j-dict-select-category
                :disabled="formDisabled"
                v-model="model.bigCategory"
                placeholder="请选择费用大类"
                parentCode="A01A03"
                :async="true"
                @input="modifyCategory"/>
              <!-- <j-dict-select-tag :disabled=formDisabled type="list" v-model="model.bigCategory" dictCode="big_category_daily" placeholder="请选择费用大类" /> -->
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="费用小类" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="smallCategory">
              <j-dict-select-category
                :disabled="formDisabled || !model.bigCategory"
                v-model="model.smallCategory"
                placeholder="请选择费用小类"
                :parentCode="model.bigCategory"
                :async="true"
                @blur="modifySmallCategory"/>
              <!-- <j-dict-select-tag :disabled=formDisabled type="list" v-model="model.smallCategory" dictCode="small_category_daily" placeholder="请选择费用小类" /> -->
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="发票类型" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="isSpecial">
              <!-- 迭代八需求 - 发票类型下拉增加一个”其他“选项，其他和普票相同。 -->
              <j-dict-select-tag
                :disabled="formDisabled"
                type="list"
                @input="isSpecial"
                v-model="model.isSpecial"
                dictCode="cost_invoice_type"
                placeholder="请选择发票类型" />
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="报销金额" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="amount">
              <a-input-number
                :disabled="formDisabled"
                :max="99999999"
                :min="0"
                @change="inputAmount(2)"
                v-model="model.amount"
                placeholder="请输入报销金额"
                style="width: 100%" />
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="税费金额" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="taxation">
              <a-input-number
                :disabled="formDisabled || isSpecialDisabled"
                :max="model.amount"
                :min="0"
                @change="inputAmount(2)"
                v-model="model.taxation"
                placeholder="请输入税费金额"
                style="width: 100%" />
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="未税金额" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="untaxedAmount">
              <a-input-number
                :max="99999999"
                :min="0"
                v-model="model.untaxedAmount"
                placeholder="请输入未税金额"
                style="width: 100%"
                disabled />
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="税率(%)" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="taxRate">
              <a-input-number
                :disabled="formDisabled || isTaxRateDisabled"
                :max="99999999"
                :min="0"
                :precision="0"
                v-model="model.taxRate"
                placeholder="请输入税率"
                style="width: 100%" />
            </a-form-model-item>
          </a-col>
          <a-input :disabled="formDisabled" v-model="model.checkPosition" placeholder="审核岗位" :hidden="true"></a-input>
        </a-row>
      </a-form-model>
    </j-form-container>
  </a-spin>
</template>

<script>
  import SelectProjectTaskInput from '@/views/scy/components/SelectProjectTaskInput'
  import SelectProjectInput from '@/views/scy/components/SelectProjectInput'
  import SelectTeamInput from '@/views/scy/components/SelectTeamInput'
  import JDictSelectCategory from '@/components/dict/JDictSelectCategory.vue'
  import SelectContractManagerInput from '@/views/scy/components/SelectContractManagerInput'

  export default {
    name: 'ErpFinanceReimbursementDailyFeeInfoForm',
    components: {
      SelectProjectTaskInput,
      SelectProjectInput,
      SelectTeamInput,
      JDictSelectCategory,
      SelectContractManagerInput
    },
    props: {
      // 表单禁用
      disabled: {
        type: Boolean,
        default: false,
        required: false
      },
      showFlowSubmitButton: {
        type: Boolean,
        default: false,
        required: false
      },
      teamId: {
        type: String,
        default: null
      },
      applicant: {
        type: String,
        default: null
      }
    },
    data () {
      return {
        contentFlag: false,
        isSpecialDisabled: false,
        isTaxRateDisabled: false,
        model: {
        },
        labelCol: {
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 24 }
        },
        confirmLoading: false,
        validatorRules: {
          taskCategory: [
              { required: true, message: '请选择业务分类!' }
          ],
          amount: [
              { required: true, pattern: /^(([1-9][0-9]*)|([0]\.\d{0,2}|[1-9][0-9]*\.\d{0,2}))$/, message: '请输入正确的金额!' }
          ],
          taxRate: [
              { required: true, message: '请输入正确的税率!' }
            ],
          isSpecial: [
              { required: true, message: '请选择发票类型!' }
          ],
          projectId: [
              { required: true, message: '请选择项目!' }
          ],
          bigCategory: [
              { required: true, message: '请选择费用大类!' }
          ],
          smallCategory: [
              { required: true, message: '请选择费用小类!' }
          ]
        },
        url: {
          add: '/api/erp/finance/reimbursement/erpFinanceReimbursementDailyFeeInfo/add',
          edit: '/api/erp/finance/reimbursement/erpFinanceReimbursementDailyFeeInfo/edit',
          queryById: '/api/erp/finance/reimbursement/erpFinanceReimbursementDailyFeeInfo/queryById'
        }
      }
    },
    computed: {
      formDisabled() {
        return this.disabled
      }
    },
    created () {
       // 备份model原始值
      this.modelDefault = JSON.parse(JSON.stringify(this.model));
    },
    methods: {
       // 修改小类
      modifySmallCategory(data) {
        if (data) {
          this.$set(this.model, 'checkPosition', data[0].checkPosition);
        }
      },
      // 修改大类，清空小类
      modifyCategory(data) {
        if (data) {
          if (this.model.smallCategory) {
            this.$set(this.model, 'smallCategory', null);
          }
        }
      },
      // 发票类型
      isSpecialInit(isEdit) {
          // if (this.model.isSpecial == 0) { // 普票
          //     this.$refs.form.clearValidate('taxation');
          //     this.$set(this.validatorRules, 'taxation', [{ required: false, pattern: /^(([1-9][0-9]*|0)|([0]\.\d{0,2}|[1-9][0-9]*\.\d{0,2}))$/, message: '请输入正确的金额!' }]);
          //     this.isSpecialDisabled = true;
          // } else if (this.model.isSpecial == 2) { // 其他
          //   this.$set(this.validatorRules, 'taxation', [{ required: false, pattern: /^(([1-9][0-9]*|0)|([0]\.\d{0,2}|[1-9][0-9]*\.\d{0,2}))$/, message: '请输入正确的金额!' }]);
          //   this.isSpecialDisabled = false;
          // } else if (this.model.isSpecial == 1) { // 专票
          //   this.$set(this.validatorRules, 'taxation', [{ required: true, pattern: /^(([1-9][0-9]*)|([0]\.\d{0,2}|[1-9][0-9]*\.\d{0,2}))$/, message: '请输入正确的金额!' }]);
          //   this.isSpecialDisabled = false;
          // }
          // if (isEdit != 1) { // 从edit进来的不改成0
          //   this.$set(this.model, 'taxation', 0);
          // }
          if(this.model.isSpecial == 0){ // 普票：税费和税率默认为0，发起人不可编辑和修改（流程中也不可修改）
            // this.$set(this.model, 'taxation',0);
            // this.$set(this.model, 'taxRate',0);
            this.$delete(this.validatorRules, 'taxation');
            this.$delete(this.validatorRules, 'taxRate');
            this.$refs.form.clearValidate('taxation');
            this.$refs.form.clearValidate('taxRate');
            // this.$set(this.validatorRules, 'taxation', [{ required: false,pattern: /^(([1-9][0-9]*|0)|([0]\.\d{0,2}|[1-9][0-9]*\.\d{0,2}))$/, message: '请输入正确的金额!'}]);
            this.isSpecialDisabled=true;
            this.isTaxRateDisabled=true;
        }else if (this.model.isSpecial == 1){ // 专票：税费和税率为必填，发起人可编辑和修改 （税率计算公式：税费金额/未税金额取整，流程中都可修改）
          this.$refs.form.clearValidate('taxation');
          // this.$set(this.model, 'taxation',null);
          // this.$set(this.model, 'taxRate',null);
          this.$set(this.validatorRules, 'taxRate', [{ required: true, message: '请输入正确的税率!'}]);
          this.$set(this.validatorRules, 'taxation', [{ required: true,pattern: /^(([1-9][0-9]*)|([0]\.\d{0,2}|[1-9][0-9]*\.\d{0,2}))$/, message: '请输入正确的金额!'}]);
          this.isSpecialDisabled=false;
          this.isTaxRateDisabled=false;
        } else { // 其他或者不填：税费金额必填默认为0，发起人可修改，税率默认为0，发起人不可编辑和修改（流程中可以修改税费金额，不可修改税率）
          // this.$set(this.model, 'taxation',0);
          // this.$set(this.model, 'taxRate',0);
          this.$delete(this.validatorRules, 'taxRate');
          this.$set(this.validatorRules, 'taxation', [{ required: true,pattern: /^(([0-9][0-9]*)|([0]\.\d{0,2}|[1-9][0-9]*\.\d{0,2}))$/, message: '请输入正确的金额!'}]);
          this.$refs.form.clearValidate('taxRate');
          this.isSpecialDisabled=false;
          this.isTaxRateDisabled=true;
        }
      },
      // 发票类型
      isSpecial(isEdit) {
          // if (this.model.isSpecial == 0) { // 普票
          //     this.$refs.form.clearValidate('taxation');
          //     this.$set(this.validatorRules, 'taxation', [{ required: false, pattern: /^(([1-9][0-9]*|0)|([0]\.\d{0,2}|[1-9][0-9]*\.\d{0,2}))$/, message: '请输入正确的金额!' }]);
          //     this.isSpecialDisabled = true;
          // } else if (this.model.isSpecial == 2) { // 其他
          //   this.$set(this.model, 'taxation', 0);
          //   this.$refs.form.clearValidate('taxation');
          //   this.$set(this.validatorRules, 'taxation', [{ required: false, pattern: /^(([1-9][0-9]*|0)|([0]\.\d{0,2}|[1-9][0-9]*\.\d{0,2}))$/, message: '请输入正确的金额!' }]);
          //   this.isSpecialDisabled = false;
          // } else if (this.model.isSpecial == 1) { // 专票
          //   this.$refs.form.clearValidate('taxation');
          //   this.$set(this.validatorRules, 'taxation', [{ required: true, pattern: /^(([1-9][0-9]*)|([0]\.\d{0,2}|[1-9][0-9]*\.\d{0,2}))$/, message: '请输入正确的金额!' }]);
          //   this.isSpecialDisabled = false;
          // }
          // if (isEdit != 1) { // 从edit进来的不改成0
          //   this.$set(this.model, 'taxation', 0);
          // }
          // 0 普票 1专票 2其他
        if(this.model.isSpecial == 0){ // 普票：税费和税率默认为0，发起人不可编辑和修改（流程中也不可修改）
            this.$set(this.model, 'taxation',0);
            this.$set(this.model, 'taxRate',0);
            this.$delete(this.validatorRules, 'taxation');
            this.$delete(this.validatorRules, 'taxRate');
            this.$refs.form.clearValidate('taxation');
            this.$refs.form.clearValidate('taxRate');
            this.isSpecialDisabled=true;
            this.isTaxRateDisabled=true;
        }else if (this.model.isSpecial == 1){ // 专票：税费和税率为必填，发起人可编辑和修改 （税率计算公式：税费金额/未税金额取整，流程中都可修改）
          this.$refs.form.clearValidate('taxation');
          this.$set(this.model, 'taxation',null);
          this.$set(this.model, 'taxRate',null);
          this.$set(this.validatorRules, 'taxRate', [{ required: true, message: '请输入正确的税率!'}]);
          this.$set(this.validatorRules, 'taxation', [{ required: true,pattern: /^(([1-9][0-9]*)|([0]\.\d{0,2}|[1-9][0-9]*\.\d{0,2}))$/, message: '请输入正确的金额!'}]);
          this.isSpecialDisabled=false;
          this.isTaxRateDisabled=false;
        } else { // 其他或者不填：税费金额必填默认为0，发起人可修改，税率默认为0，发起人不可编辑和修改（流程中可以修改税费金额，不可修改税率）
          this.$set(this.model, 'taxation',0);
          this.$set(this.model, 'taxRate',0);
          this.$delete(this.validatorRules, 'taxRate');
          this.$set(this.validatorRules, 'taxation', [{ required: true,pattern: /^(([0-9][0-9]*)|([0]\.\d{0,2}|[1-9][0-9]*\.\d{0,2}))$/, message: '请输入正确的金额!'}]);
          this.$refs.form.clearValidate('taxation');
          this.$refs.form.clearValidate('taxRate');
          this.isSpecialDisabled=false;
          this.isTaxRateDisabled=true;
        }
          this.inputAmount();
      },
      // 输入报销金额
      inputAmount() {
        // 判断当有值的
        if(this.model.taxation === null || this.model.taxation === '' || this.model.taxation === undefined){
          this.$set(this.model,'untaxedAmount', null);
          return false
        }
        if (this.model.taxation != undefined && this.model.taxation != null) {
          let untaxedAmount = (this.model.amount - this.model.taxation).toFixed(2);
          if (untaxedAmount > 0) {
            this.$set(this.model, 'untaxedAmount', untaxedAmount);
            if (this.model.isSpecial == 1) {
              this.$set(this.model, 'taxRate', (this.model.taxation / this.model.untaxedAmount * 100).toFixed(0));
            } else {
              this.$set(this.model, 'taxRate',0);
            }
          } else {
            this.$set(this.model, 'untaxedAmount', 0);
            this.$set(this.model, 'taxRate', 0);
          }
        }
      },
      changeTask(data) {
        if (data) {
            this.model.taskName = data[0].taskDescription
        }
      },
      selectProject(data) {
        if (data) {
          if (data.choseObj) {
            
          }
          if (data.choseObj && data.choseObj.length) {
            this.model.projectCode = data.choseObj[0].finalNo
            this.model.performanceAttributionYear = data.choseObj[0].year;
          } else {
            this.model.projectCode = null
            this.model.performanceAttributionYear = null
          }
          if (this.model.taskCategory) {
            this.$set(this.model, 'taskName', null);
            this.$set(this.model, 'taskCategory', '');
          }
          if (this.model.relContractId) {
            this.$set(this.model, 'relContractId', null);
          }
        }
      },
      add (flag) {
        this.edit(this.modelDefault);
        this.contentFlag = flag;
      },
      edit (record, flag) {
        this.$refs['form'].clearValidate();
        Object.assign(this.$data, this.$options.data())
        this.model = Object.assign({}, record);
        this.isSpecialInit(1);
        this.contentFlag = flag;
        this.visible = true;
      },
      submitForm () {
        const that = this;
        // 触发表单验证
        this.$refs.form.validate(valid => {
          if (valid) {
            // that.confirmLoading = true;
            if (!this.model.id) {
              this.model.id = parseInt(Math.random() * 1000000000000);
            }
            that.$emit('ok', this.model);
            // let httpurl = '';
            // let method = '';
            // if(!this.model.id){
            //   httpurl+=this.url.add;
            //   method = 'post';
            // }else{
            //   httpurl+=this.url.edit;
            //    method = 'put';
            // }
            // httpAction(httpurl,this.model,method).then((res)=>{
            //   if(res.success){
            //     that.$message.success(res.message);
            //     that.$emit('ok');
            //   }else{
            //     that.$message.warning(res.message);
            //   }
            // }).finally(() => {
            //   that.confirmLoading = false;
            // })
          }
        })
      }
    }
  }
</script>
